var config = require("nconf");
var passport = require('passport');
var AuthLocalStrategy = require('passport-local').Strategy;
var AuthFacebookStrategy = require('passport-facebook').Strategy;
var AuthVKStrategy = require('passport-vkontakte').Strategy;
var TwitterStrategy = require('passport-twitter').Strategy;
var GoogleStrategy = require('passport-google-oauth').OAuth2Strategy;
var InstagramStrategy  = require('passport-instagram').Strategy;
var FoursquareStrategy = require('passport-foursquare').Strategy;

var request = require("request");

//function checkUserByProfileId (profile, done) {
//    request({
//        uri: config.get("app:api_address") + "/socAccs/" + profile.id,
//        method: "GET",
//        timeout: 500,
//        followRedirect: true,
//        maxRedirects: 5
//    }, function(error, response, body) {
//        if(JSON.parse(body).soccAcc == null){
//            request({
//                uri: config.get("app:api_address") + "/socAccs",
//                method: "POST",
//                form: {
//                    act: "add",
//                    society: profile.provider,
//                    account: profile.profileUrl,
//                    profileId: profile.id
//                }
//            }, function(error, response, body) {
//                console.log(body);
//                checkUserByProfileId(profile, done);
//            });
//
//        }
//
//        else {
//            var account = JSON.parse(body).soccAcc;
//            console.log(account);
//            return done(null, {
//                // user stuff
//                username: profile.displayName,
//                photoUrl: "https://graph.facebook.com/" + profile.id + "/picture?width=200&height=200",
//                profileUrl: profile.profileUrl
//            });
//        }
//    });
//}

// method returns user stuff
function returnUser(profile, done){
    var user = {
        username: "",
        photoUrl: "",
        profileUrl: ""
    };
    console.log(profile.provider);
    switch (profile.provider)
    {
        case "facebook":
            return done(null, {
                photoUrl: "https://graph.facebook.com/" + profile.id + "/picture?width=200&height=200",
                profileUrl: profile.profileUrl,
                username: profile.displayName
            });
            break;
        case "vkontakte":
            request({
                uri: "https://api.vk.com/method/users.get?user_id=" + profile.id + "&fields=photo_200",
                method: "GET",
                timeout: 500,
                followRedirect: true,
                maxRedirects: 10
            }, function(error, response, body) {
                return done(null, {
                    photoUrl: JSON.parse(body).response[0].photo_200,
                    profileUrl: profile.profileUrl,
                    username: profile.displayName
                });

            });
            break;
        case "twitter":
            return done(null, {
                photoUrl: profile.photos[0].value.replace("normal", "200x200"),
                profileUrl: "https://twitter.com/" + profile.username,
                username: profile.displayName
            });
            break;
        case "google":
            process.nextTick(function () {
                return done(null, {
                    photoUrl: profile._json.picture + "?sz=200",
                    profileUrl: profile._json.link,
                    username: profile.displayName
                })
            });
            break;
        default:
            break;
    }
}

passport.use('local', new AuthLocalStrategy(
    function (username, password, done) {

        if (username == "admin" && password == "admin") {
            return done(null, {
                username: "admin",
                photoUrl: "https://pp.vk.me/c7003/v7003079/374b/53lwetwOxD8.jpg",
                profileUrl: "http://vk.com/durov"
            });
        }

        return done(null, false, {
            message: 'Неверный логин или пароль'
        });
    }
));

passport.use('facebook', new AuthFacebookStrategy({
        clientID: config.get("auth:fb:app_id"),
        clientSecret: config.get("auth:fb:secret"),
        callbackURL: config.get("app:url") + "/auth/fb/callback",
        profileFields: [
            'id',
            'displayName',
            'profileUrl',
            "gender",
            "photos"
        ]
    },
    function (accessToken, refreshToken, profile, done) {
        return returnUser(profile, done);
    }
));



passport.use('vk', new AuthVKStrategy({
        clientID: config.get("auth:vk:app_id"),
        clientSecret: config.get("auth:vk:secret"),
        callbackURL: config.get("app:url") + "/auth/vk/callback"
    },
    function (accessToken, refreshToken, profile, done) {
        return returnUser(profile, done);
    }
));

passport.use(new TwitterStrategy({
    consumerKey: config.get("auth:twitter:access_token"),
    consumerSecret: config.get("auth:twitter:access_token_secret"),
    callbackURL: config.get("app:url") + "/auth/twitter/callback"
  },
    function(token, tokenSecret, profile, done) {
        return returnUser(profile, done);
  }
));

passport.use(new GoogleStrategy({
        clientID: config.get("auth:google:google_client_id"),
        clientSecret: config.get("auth:google:google_client_secret"),
        callbackURL: config.get("app:url") + "/auth/google/callback"
    },
    function(accessToken, refreshToken, profile, done) {
        // asynchronous verification, for effect...
        return returnUser(profile, done);
    }
));

passport.use(new InstagramStrategy({
        clientID: config.get("auth:instagram:instagram_client_id"),
        clientSecret: config.get("auth:instagram:instagram_client_secret"),
        callbackURL: config.get("app:url") + "/auth/instagram/callback"
    },
    function(accessToken, refreshToken, profile, done) {
        // asynchronous verification, for effect...
        process.nextTick(function () {

            // To keep the example simple, the user's Instagram profile is returned to
            // represent the logged-in user.  In a typical application, you would want
            // to associate the Instagram account with a user record in your database,
            // and return that user instead.
            return done(null, profile);
        });
    }
));

passport.use(new FoursquareStrategy({
        clientID: config.get("auth:foursquare:foursquare_client_id"),
        clientSecret: config.get("auth:foursquare:foursquare_client_secret"),
        callbackURL: "http://127.0.0.1:3000/auth/foursquare/callback"
    },
    function(accessToken, refreshToken, profile, done) {
        // asynchronous verification, for effect...
        process.nextTick(function () {

            // To keep the example simple, the user's Foursquare profile is returned
            // to represent the logged-in user.  In a typical application, you would
            // want to associate the Foursquare account with a user record in your
            // database, and return that user instead.
            return done(null, profile);
        });
    }
));


passport.serializeUser(function (user, done) {
    done(null, JSON.stringify(user));
});


passport.deserializeUser(function (data, done) {
    try {
        done(null, JSON.parse(data));
    } catch (e) {
        done(err)
    }
});

module.exports = function (app) {
};